package com.example.sxy.remoteservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.example.sxy.servicedemo.ServiceInterface;


public class MainActivity extends Activity {
    private ServiceInterface remoteService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        绑定远程服务（属于另外一个应用程序）
        Button bindService = (Button) findViewById(R.id.button1);
        bindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.sxy.servicedemo.ServiceInterface");
//                没有service的时候会创建一个service
                bindService(intent, connection, BIND_AUTO_CREATE);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
//    建立与远程服务的连接
private ServiceConnection connection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        remoteService = ServiceInterface.Stub.asInterface(service);
        try {
            int result = remoteService.plus(50, 50);
            String upperStr = remoteService.toUpperCase("remote success!!!");
            Log.d("RemoteService", "result is " + result);
            Log.d("RemoteService", "upperStr is " + upperStr);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
};
}
